package com.example.blog.controller.admin;

import com.example.blog.pojo.User;
import com.example.blog.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * name: 东北宋小宝
 * date: 2020/8/13
 */
@Controller
@RequestMapping("/admin")
public class LoginController {
    @Resource
    private UserService userService;
    @GetMapping
    public String loginPage(){
        return "admin/login";
    }
    @GetMapping("/main")
    public String success(){
        return "admin/index";
    }
    @GetMapping("/creat")
    public String creat(){
        return "admin/creat";
    }
    @PostMapping("/save")
    public String toCreat(User user){
        userService.saveUser(user);
        return "";
    }
    @PostMapping("/login")
    public String toLogin(@RequestParam String username, @RequestParam String password, HttpSession session, RedirectAttributes attributes){

        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        try {
            SecurityUtils.getSubject().login(usernamePasswordToken);
        }  catch (IncorrectCredentialsException ice) {
            System.out.println("密码错误");
        } catch (UnknownAccountException uae) {
            System.out.println("账号不存在");
        } catch (LockedAccountException e) {
            System.out.println("账号被锁定");
        } catch (ExcessiveAttemptsException eae) {
            System.out.println("操作频繁，请稍后再试");
        }
        return "redirect:/admin/main";
    }
    @GetMapping("/logout")
    public String exit(HttpSession session){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/admin";
    }
}
